package com.sun.order.intercepter;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sun.commons.utils.CookieUtils;
import com.sun.commons.utils.HttpClientUtil;
import com.sun.commons.utils.JsonUtils;
import com.sun.order.service.CommonConfig;

public class LoginIntercepter extends HandlerInterceptorAdapter{

	@Resource
	private CommonConfig commonConfig;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = CookieUtils.getCookieValue(request, commonConfig.cookie_token);
		String loginhref = commonConfig.passport_login_href;
		//cookie无token  跳转登录
		if(token==null || token.equals("")){
			response.sendRedirect(loginhref);
			return false;
		}
		String result = HttpClientUtil.doPost(commonConfig.passport_usertoken_href+token);
		@SuppressWarnings("unchecked")
		Map<String,Object> resMap = JsonUtils.jsonToPojo(result, Map.class);
		String status = resMap.get("status").toString();
		if(!status.equals("200")){//获取不到登陆用户信息  则断定登陆状态已失效
			StringBuffer requestURL = request.getRequestURL();
			response.sendRedirect(loginhref+"?cartUrl="+requestURL.toString());
		}
		return true;
	}
	
}
